package cn.ctodb.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.ctodb.domain.Tag;
import cn.ctodb.repository.ContentRepository;
import cn.ctodb.repository.TagRepository;

@Service
public class TagService {

    @Resource
    private ContentRepository contentRepository;
    @Resource
    private TagRepository     tagRepository;

    public Page<Tag> getTags(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    public void setTags(String tags) {
        if (tags == null) return;
        for (String tag : tags.split("[,]")) {
            if ("".equals(tag.trim())) continue;
            Tag t = tagRepository.findByName(tag);
            if (t != null) {
                int i = contentRepository.countByTagsLike(tag);
                t.setArticleCount(i);
                tagRepository.save(t);
            } else {
                t = new Tag();
                t.setName(tag);
                t.setArticleCount(1);
                tagRepository.save(t);
            }
        }
    }

    public void clearTags() {
        List<Tag> list = tagRepository.findAll();
        for (Tag t : list) {
            try {
                int i = contentRepository.countByTagsLike(t.getName());
                t.setArticleCount(i);
                tagRepository.save(t);
            } catch (Exception e) {
            }
        }
    }

}
